/**
 * 地图工具
 * 快速查询（直接查询建筑物或POI点）：polygonDraw 、rectangleDraw 、circleDraw
 * 邻域查询：cilcleMarkerDraw
 * 空间分析：cilcleMarkerDraw、polineDraw、polygonDraw 、rectangleDraw 、circleDraw
 * 缓冲分析：polineDraw、polygonDraw 、rectangleDraw 、circleDraw
 */
import sgisSpatialQuery from "./sfgis.spatial.query.js";
import sgisRegionBase from "./sfgis.region.base.js";
// 高亮图层
import hlLayer from "./lib/systemlayers/hl.layer";
// 区划标签
import regionLable from "./lib/systemlayers/region.marker.layer";
import sgisMapBase from "./sfgis.map.base";
//绘图工具
import 'mapbox-gl-draw-sf/dist/mapbox-gl-draw.css';
import MapboxDraw from 'mapbox-gl-draw-sf/dist/mapbox-gl-draw';

export default {
  /**
   * 初始化地图绘制控件
   */
  activeMap: null,
  DrawCon: null,
  drawControl: null, // 地图绘制工具
  isMeasure: false, // 判断绘制之后是查询还是测量，默认为false即查询
  drawLayers:null,// 测量图层
  isDrawInit: false, // 绘制工具初始化标识
  spatialTypes: {
    // 空间查询类型
    SPATIAL: "SPATIAL", // 空间查询  用户自己选择查询对象
    BUFFER: "BUFFER", // 缓冲分析，自由选择缓冲地物河流、道路等查询区划
    VICINITY: "VICINITY", // 邻域分析  针对区划
    QUICK: "QUICK" // 快速查询  针对建筑物，圆选、框选、多边形选，直接针对建筑物进行快速查询
  },
  currSpatialType: "SPATIAL", // 当前绘制结果查询类型
  /**
   * 空间查询的类型默认为查询 1=普通区划所有的面数据集及点数据集名称根据level计算，
   *  如果要查询 3 = 特色区，2 = 高新区，则需要手动指定面数据集及点数据集的名称
   */
  regiontype: "1",
  tsDtaSetName: "", // 特色区划面
  level: "0",
  bufferTypes: {
    DRAW: "DRAW", // 绘制，，，，以绘制的区域进行缓存分析
    SELECT: "SELECT" // 选择地物，通过绘制的图形获取到对应类型的地物，如河流、道路、铁路等
  },
  currBufferType: "", // 当前缓冲类型
  bufferDistance: 0, // 缓冲距离
  bufferDataSetName: "", // 缓存分析地物所在的面
  drawType: {
    CIRCLEMARKER: "CIRCLEMARKER",
    POLINE: "POLINE",
    POLYGON: "POLYGON",
    RECTANGLE: "RECTANGLE",
    CIRCLE: "CIRCLE"
  },
  // 绘制工具上次绘制结果
  lastDraw:null,
  lastGeometry:null,
  init(map) {
    // mapbox初始化绘图工具

    // 为底图增加绘制工具
    this.DrawCon = new MapboxDraw();
    map.addControl(this.DrawCon,'top-right')
    sgisMapBase.setDraw(this.DrawCon);
    // 增加导航工具
    map.addControl(new mapboxgl.NavigationControl());
    // 隐藏系统绘制工具
    $(".mapbox-gl-draw_ctrl-draw-btn").hide();

    this.isDrawInit = true;
    this.activeMap = map;
    // 绘制成功后执行，进行查询,并不是所有的绘制都要进行数据分析的，如量算，这个地方就要按类型进行过滤
    let _this = this;
    map.on('draw.create',function(res) {// 圆和矩形不知道为什么执行了两次，改源码要怎么阻止一次？？？
      // 记录本次并移除上次绘制结果
      if(_this.lastDraw === null){
        _this.lastDraw = (_this.DrawCon.getAll()).features[0];
      }else {
        if((_this.DrawCon.getAll()).features.length>1){//由于重复绘制，增加长度判断
          if(_this.lastDraw){
            _this.DrawCon.delete(_this.lastDraw.id);
          }
        }
        _this.lastDraw = (_this.DrawCon.getAll()).features[0];
      }
      const drawFeatures = res.features;

      if(drawFeatures && drawFeatures !== undefined && drawFeatures.length > 0){
        const drawFeature = drawFeatures[0];
        if(drawFeature.properties !== undefined){
          const drawType = drawFeature.properties.draw_type;
          let geometry = null;
          if(drawType === "point" || drawFeature.geometry.type === "Point"){
            geometry = drawFeature.geometry;
            if(_this.lastGeometry !==null &&
              _this.lastGeometry.coordinates[0] === geometry.coordinates[0] &&
              _this.lastGeometry.coordinates[1] === geometry.coordinates[1]){
              return;
            }
          }else if(drawType === "line"){
            geometry = drawFeature.geometry;
          }else if(drawType === "circle"){
            geometry = drawFeature.geometry;
          }else if(drawType === "rectangle"){
            geometry = drawFeature.geometry;
            if(_this.lastGeometry !==null &&
              _this.equar(_this.lastGeometry.coordinates,geometry.coordinates)){
              return;
            }
          }else if(drawType === "polygon"){
            geometry = drawFeature.geometry;
          }
          if(geometry === null){
            return;
          }
          _this.lastGeometry = geometry;
          if(!_this.isMeasure){
            //暂时这样写，先不支持圆，矩形
            geometry = _this.DrawCon.getAll().features[0].geometry;
            //执行查询，查询完后添加到地图还没做
            _this._query(null, geometry);
          }else{
            _this.measured(drawFeature,_this.activeMap);
          }
        }
      }
    });
    map.on('draw.update', function (res) {
      const drawFeatures = res.features;
      const drawFeature = drawFeatures[0];
      if(drawFeatures && drawFeatures !== undefined && drawFeatures.length > 0){
        if(_this.isMeasure){
          _this.measured(drawFeature,_this.activeMap);
        }
      }
    });
    /* ************ 初始化地图绘制工具结束 **********************/
  },
  /**
   * 由于矩形绘制两次，这个地方判断一下两次绘制是否相同
   * @param a
   * @param b
   * @returns {boolean}
   */
  equar(a, b) {
  if (a.length !== b.length) {
    return false
  } else {
    // 循环遍历数组的值进行比较
    for (let i = 0; i < a.length; i++) {
      let ai = a[i];
      let bi = b[i];
      if(ai.length !== bi.length){
        return false;
      }
      for(let j = 0;j < ai.length; j++){
        if(ai[j][0] !== bi[j][0] || ai[j][1] !== bi[j][1]){
          return false;
        }
      }
    }
    return true;
  }
},
  // 查询完毕后重置初始参数
  _restInitParams() {
    this.currSpatialType = "SPATIAL";
    this.regiontype = "1";
    this.tsDtaSetName = ""; // 特色区划面
    this.level = "0";
    this.bufferDataSetName = ""; // 缓存分析地物所在的面
    this.currBufferType = ""; // 当前缓冲类型
    this.bufferDistance = 0; // 缓冲距离
  },
  /**
   * 点绘制(空间分析 换从分析  邻域分析)
   */
  _circleMarkerDraw() {
    this.isMeasure = false;
    this.DrawCon.changeMode('draw_point');
  },
  /**
   * 线绘制(空间分析 缓冲分析分析)
   */
  _polineDraw() {
    this.isMeasure = false;
    this.DrawCon.changeMode('draw_line_string');
  },
  /**
   * 多边形选择(快速查询 空间分析 缓冲分析分析)
   */
  _polygonDraw() {
    this.isMeasure = false;
    this.DrawCon.changeMode('draw_polygon');
  },
  /**
   * 矩形绘制(快速查询 空间分析 缓冲分析分析)
   */
  _rectangleDraw() {
    this.isMeasure = false;
    this.DrawCon.changeMode('draw_rectangle');
  },
  /**
   * 圆绘制(快速查询 空间分析 缓冲分析分析)
   */
  _circleDraw() {
    this.isMeasure = false;
    this.DrawCon.changeMode('draw_circle');
  },
  /**
   * 空间查询
   * gometry 空间对象
   * dataSetName 数据集名称
   */
  _spatialQueryByLevel(gometry, dataSetName) {
    let currRcid = sgisRegionBase.regionCatalog.getRegionCatalogs().id;
    let _this = this;
    sgisSpatialQuery.spatialQuery(gometry, dataSetName, function(e) {
      if (e && e.result && e.result.features) {
        let regioninfos = [];
        let sqlCondiftionArr = new Array();
        let features = [];
        for (let i = 0; i < e.result.features.features.length; i++) {
          let feature = e.result.features.features[i];
          let regioninfo = {
            id: feature.properties.QH_CODE,
            rcid: currRcid,
            regioncode: feature.properties.QH_CODE,
            regionname: feature.properties.QH_NAME,
            regiontype: _this.regiontype,
            regionlevel: _this.regionlevel,
            origincode: "",
            parcode: "",
            lat: "",
            lon: "",
            rname: dataSetName,
            pname: dataSetName.replace("ST_R", "ST_P")
          };
          features.push(feature);
          regioninfos.push(regioninfo);
          sqlCondiftionArr.push(
            "QH_CODE = '" + feature.properties.QH_CODE + "'"
          );
        }
        if(features.length<1){
          return false;
        }

        _this.clearAllDrawFeatures();
        //更新区划面板数据
        EventBus.$emit("changeToolRegion", regioninfos,"spatialQuery");
        // 保存一下区划
        sgisRegionBase.regionInfos.setCurrentRegionInfos(regioninfos);
        //刷新features要搞成mapbox的方式
        // hlLayer.refreshBoundaryFeatures(e.result.features, _this.activeMap,"fill");
        // 查询添加添加区划标签  空间查询
        let stPName = dataSetName.replace("ST_R", "ST_P");
        let sqlCondition = sqlCondiftionArr.join(" or ");
        sgisSpatialQuery.queryAttributeBySQL(
          stPName,
          sgisRegionBase.regionCatalog.getCurrDataSource(),
          sqlCondition,
          function(e) {
            let regioninfos = [];
            for (let j = 0; j < e.result.recordsets.length; j++) {
              let rfeatures = e.result.recordsets[j].features;
              for (let i = 0; i < rfeatures.features.length; i++) {
                let feature = rfeatures.features[i];
                let regioninfo = {
                  id: feature.properties.QH_CODE,
                  rcid: currRcid,
                  regioncode: feature.properties.QH_CODE,
                  regionname: feature.properties.QH_NAME,
                  regiontype: _this.regiontype,
                  regionlevel: _this.regionlevel,
                  origincode: "",
                  parcode: "",
                  lat: feature.properties.SmY,
                  lon: feature.properties.SmX,
                  rname: dataSetName,
                  pname: stPName
                };
                regioninfos.push(regioninfo);
              }
            }
            try{
              regionLable.createLayer(regioninfos, _this.activeMap);
            }catch (e) {
              console.log(e);
            }
            _this._restInitParams();
          }
        );
      }
    });
  },
  /**
   * 邻域查询
   * gometry 空间对象
   * dataSetName 数据集名称
   * @param {Object} geometry
   * @param {String} dataSetName
   */
  _cicinityQuery(geometry, dataSetName) {
    let currRcid = sgisRegionBase.regionCatalog.getCurrRegionCatalog().id;
    let _this = this;
    sgisSpatialQuery.spatialQuery(geometry, dataSetName, function(e) {
      if (
        e &&
        e.result &&
        e.result.features &&
        e.result.features.features.length > 0
      ) {
        // 点选中的区域
        let currGeomotry = e.result.features.features[0];
        let regioninfos = [];
        let features = [];
        let sqlCondiftionArr = new Array();
        let feature = e.result.features.features[0];
        let regioninfo = {
          id: feature.properties.QH_CODE,
          rcid: currRcid,
          regioncode: feature.properties.QH_CODE,
          regionname: feature.properties.QH_NAME,
          regiontype: _this.regiontype,
          regionlevel: _this.regionlevel,
          origincode: "",
          parcode: "",
          lat: "",
          lon: "",
          rname: dataSetName,
          pname: dataSetName.replace("ST_R", "ST_P")
        };
        regioninfos.push(regioninfo);
        features.push(feature);
        sqlCondiftionArr.push("QH_CODE = '" + feature.properties.QH_CODE + "'");

        // 查询与点选区域相邻的区域
        sgisSpatialQuery.cicinityQuery(currGeomotry, dataSetName, function(re) {
          if (re && re.result && re.result.features) {
            for (let i = 0; i < re.result.features.features.length; i++) {
              let feature = re.result.features.features[i];
              let regioninfo = {
                id: feature.properties.QH_CODE,
                rcid: currRcid,
                regioncode: feature.properties.QH_CODE,
                regionname: feature.properties.QH_NAME,
                regiontype: _this.regiontype,
                regionlevel: _this.regionlevel,
                origincode: "",
                parcode: "",
                lat: "",
                lon: "",
                rname: dataSetName,
                pname: dataSetName.replace("ST_R", "ST_P")
              };
              regioninfos.push(regioninfo);
              sqlCondiftionArr.push(
                "QH_CODE = '" + feature.properties.QH_CODE + "'"
              );
              features.push(feature);
            }
          }
          // 保存一下区划
          sgisRegionBase.regionInfos.setCurrentRegionInfos(regioninfos);
          let geometry = {
            features:features,
            type: "FeatureCollection"
          };
          hlLayer.refreshBoundaryFeatures(geometry, _this.activeMap,"fill");
          // 查询添加添加区划标签  空间查询
          let stPName = dataSetName.replace("ST_R", "ST_P");
          let sqlCondition = sqlCondiftionArr.join(" or ");
          sgisSpatialQuery.queryAttributeBySQL(
            stPName,
            sgisRegionBase.regionCatalog.getCurrDataSource(),
            sqlCondition,
            function(e) {
              let regioninfos = [];
              for (let j = 0; j < e.result.recordsets.length; j++) {
                let rfeatures = e.result.recordsets[j].features;
                for (let i = 0; i < rfeatures.features.length; i++) {
                  let feature = rfeatures.features[i];
                  let regioninfo = {
                    id: feature.properties.QH_CODE,
                    rcid: currRcid,
                    regioncode: feature.properties.QH_CODE,
                    regionname: feature.properties.QH_NAME,
                    regiontype: _this.regiontype,
                    regionlevel: _this.regionlevel,
                    origincode: "",
                    parcode: "",
                    lat: feature.properties.SmY,
                    lon: feature.properties.SmX,
                    rname: dataSetName,
                    pname: stPName
                  };
                  regioninfos.push(regioninfo);
                }
              }
              regionLable.createLayer(regioninfos, _this.activeMap);
              _this._restInitParams();
            }
          );
        });
      } else {
        _this._restInitParams();
        return;
      }
    });
  },
  /**
   * 快速查询 直接查询的建筑物，当前直接查询建筑物点，建筑物没有面
   * @param gemetry
   * @param dataSetName
   * @private
   */
  _quckQuery(gometry,dataSetName){
    if(this.activeMap.getZoom() < 11){
      alert("地图缩放层级低，请缩放地图到村级");
      return;
    }
    let currRcid = sgisRegionBase.regionCatalog.getRegionCatalogs().id;
    let _this = this;
    sgisSpatialQuery.spatialQuery(gometry, dataSetName, function(e) {
      if (e && e.result && e.result.features) {
        let regioninfos = [];
        let sqlCondiftionArr = new Array();
        let features = [];
        for (let i = 0; i < e.result.features.features.length; i++) {
          let feature = e.result.features.features[i];
          let regioninfo = {
            id: feature.properties.QH_CODE,
            rcid: currRcid,
            regioncode: feature.properties.QH_CODE,
            regionname: feature.properties.QH_NAME,
            regiontype: _this.regiontype,
            regionlevel: _this.regionlevel,
            origincode: "",
            parcode: "",
            lat: (feature.properties.Smy === undefined) ? feature.properties.SMY : feature.properties.Smy,
            lon: (feature.properties.Smx === undefined) ? feature.properties.SMX : feature.properties.Smx,
            rname: dataSetName,
            pname: dataSetName.replace("ST_R", "ST_P")
          };
          features.push(feature);
          regioninfos.push(regioninfo);
          sqlCondiftionArr.push(
            "QH_CODE = '" + feature.properties.QH_CODE + "'"
          );
        }
        //更新区划面板数据
        EventBus.$emit("changeToolRegion", regioninfos,"spatialQuery");
        // 保存一下区划
        sgisRegionBase.regionInfos.setCurrentRegionInfos(regioninfos);
        regionLable.createLayer(regioninfos, _this.activeMap);
      }
    });
  },
  /**
   * 缓冲查询
   * gometry 空间对象
   * dataSetName 数据集名称
   * @param {Object} geometry
   * @param {String} dataSetName
   */
  _bufferQuery(geometry, dataSetName, bufferDistance) {
    let currRcid = sgisRegionBase.regionCatalog.getCurrRegionCatalog().id;
    let _this = this;

    /**
     * 如果是绘制缓冲分析，则直接利用绘制的图形进行，
     * 如果是选择地物进行缓冲分析，则需要利用绘制的图形先空间查询出对应的地图然后，利用地物进行缓冲分析
     */
    if (this.currBufferType === this.bufferTypes.DRAW) {
      // 直接利用绘制范围图形进行数据缓冲
      sgisSpatialQuery.bufferQuery(
        geometry,
        dataSetName,
        bufferDistance,
        function(d, e) {
          // 添加缓冲区范围到地图
          if(e.result && e.result !== undefined){
            let bufferGeometry = e.result.resultGeometry.geometry;
            _this.addBufferLayer(bufferGeometry,_this.activeMap);
          }else {
            return;
          }

          sgisSpatialQuery.spatialQuery(e.result.resultGeometry, d, function(e) {
            if (e && e.result && e.result.features) {
              let regioninfos = [];
              let sqlCondiftionArr = new Array();
              let features = [];
              for (let i = 0; i < e.result.features.features.length; i++) {
                let feature = e.result.features.features[i];
                let regioninfo = {
                  id: feature.properties.QH_CODE,
                  rcid: currRcid,
                  regioncode: feature.properties.QH_CODE,
                  regionname: feature.properties.QH_NAME,
                  regiontype: _this.regiontype,
                  regionlevel: _this.regionlevel,
                  origincode: "",
                  parcode: "",
                  lat: "",
                  lon: "",
                  rname: dataSetName,
                  pname: dataSetName.replace("ST_R", "ST_P")
                };
                features.push(feature);
                regioninfos.push(regioninfo);
                sqlCondiftionArr.push(
                  "QH_CODE = '" + feature.properties.QH_CODE + "'"
                );
              }
              if(features.length<1){
                return false;
              }

              _this.clearAllDrawFeatures();
               //更新区划面板数据
               EventBus.$emit("changeToolRegion", regioninfos,"bufferQuery");


              // 保存一下查询到的区划西悉尼
              sgisRegionBase.regionInfos.setCurrentRegionInfos(regioninfos);
              //刷新features要搞成mapbox的方式
              // hlLayer.refreshBoundaryFeatures(
              //   e.result.features,
              //   _this.activeMap,
              //   "fill"
              // );

              // 查询添加添加区划标签 SQL查询点数据集
              let stPName = dataSetName.replace("ST_R", "ST_P");
              let sqlCondition = sqlCondiftionArr.join(" or ");
              sgisSpatialQuery.queryAttributeBySQL(
                stPName,
                sgisRegionBase.regionCatalog.getCurrDataSource(),
                sqlCondition,
                function(e) {
                  let regioninfos = [];
                  for (let j = 0; j < e.result.recordsets.length; j++) {
                    let rfeatures = e.result.recordsets[j].features;
                    for (let i = 0; i < rfeatures.features.length; i++) {
                      let feature = rfeatures.features[i];
                      let regioninfo = {
                        id: feature.properties.QH_CODE,
                        rcid: currRcid,
                        regioncode: feature.properties.QH_CODE,
                        regionname: feature.properties.QH_NAME,
                        regiontype: _this.regiontype,
                        regionlevel: _this.regionlevel,
                        origincode: "",
                        parcode: "",
                        lat: feature.properties.SmY,
                        lon: feature.properties.SmX,
                        rname: dataSetName,
                        pname: stPName
                      };
                      regioninfos.push(regioninfo);
                    }
                  }
                  try{
                    regionLable.createLayer(regioninfos, _this.activeMap);
                  }catch (e) {
                    console.log(e);
                  }
                  _this._restInitParams();
                }
              );
            }
          });
        }
      );
    } else if (this.currBufferType === this.bufferTypes.SELECT) {
      /**
       * 利用地物进行缓冲分析
       * 第一步：首先根据绘制图形进行空间查询，获取选中的地物
       *        利用地物进行缓冲时，要指定地物所在的面数据集
       */
      sgisSpatialQuery.spatialQuery(geometry, dataSetName, function(e) {
        /**
         * 第二步：利用查询出来的地物进行缓冲分析
         */
        // 查询出来的的地物可能存在多个features,需要做一下合并
        if(!e || !e.result || e.result.features.features.length < 1){
          return;
        }
        let geometrys = { type: "MultiPolygon", coordinates: null };
        let coordinates = [];
        let features= e.result.features.features;
        for(let i = 0 ; i <features.length ; i++){
          let feature = features[i];
          coordinates = coordinates.concat(feature.geometry.coordinates);
        }
        geometrys.coordinates = coordinates;
        // 合并后的多边形
        sgisSpatialQuery.bufferQuery(
          lg,
          dataSetName,
          bufferDistance,
          function(d, e) {
            /**
             * 第三步：进行空间查询
             */
            // 获取缓冲范围，并添加到图层
            // let bufferLayer = L.geoJSON(e.result.resultGeometry).addTo(
            //   _this.activeMap
            // );

            //添加缓冲范围图层到地图

            sgisSpatialQuery.spatialQuery(e.result.resultGeometry, d, function (e) {
              if (e && e.result && e.result.features) {
                let regioninfos = [];
                let sqlCondiftionArr = new Array();
                let features = [];
                for (let i = 0; i < e.result.features.features.length; i++) {
                  let feature = e.result.features.features[i];
                  let regioninfo = {
                    id: feature.properties.QH_CODE,
                    rcid: currRcid,
                    regioncode: feature.properties.QH_CODE,
                    regionname: feature.properties.QH_NAME,
                    regiontype: _this.regiontype,
                    regionlevel: _this.regionlevel,
                    origincode: "",
                    parcode: "",
                    lat: "",
                    lon: "",
                    rname: dataSetName,
                    pname: dataSetName.replace("ST_R", "ST_P")
                  };
                  features.push(feature);
                  regioninfos.push(regioninfo);
                  sqlCondiftionArr.push(
                    "QH_CODE = '" + feature.properties.QH_CODE + "'"
                  );
                }

                //更新区划面板数据
                EventBus.$emit("changeToolRegion", regioninfos);

                // 保存一下区划
                sgisRegionBase.regionInfos.setCurrentRegionInfos(regioninfos);
                //刷新features要搞成mapbox的方式
                // hlLayer.refreshBoundaryFeatures(
                //   e.result.features,
                //   _this.activeMap,
                //   "fill"
                // );
                // 查询添加添加区划标签  空间查询
                let stPName = dataSetName.replace("ST_R", "ST_P");
                let sqlCondition = sqlCondiftionArr.join(" or ");
                sgisSpatialQuery.queryAttributeBySQL(
                  stPName,
                  sgisRegionBase.regionCatalog.getCurrDataSource(),
                  sqlCondition,
                  function (e) {
                    let regioninfos = [];
                    for (let j = 0; j < e.result.recordsets.length; j++) {
                      let rfeatures = e.result.recordsets[j].features;
                      for (let i = 0; i < rfeatures.features.length; i++) {
                        let feature = rfeatures.features[i];
                        let regioninfo = {
                          id: feature.properties.QH_CODE,
                          rcid: currRcid,
                          regioncode: feature.properties.QH_CODE,
                          regionname: feature.properties.QH_NAME,
                          regiontype: _this.regiontype,
                          regionlevel: _this.regionlevel,
                          origincode: "",
                          parcode: "",
                          lat: feature.properties.SmY,
                          lon: feature.properties.SmX,
                          rname: dataSetName,
                          pname: stPName
                        };
                        regioninfos.push(regioninfo);
                      }
                    }
                    try{
                      regionLable.createLayer(regioninfos, _this.activeMap);
                    }catch (e) {
                      console.log(e);
                    }
                    _this._restInitParams();
                  }
                );
              }
            });
          }
        );
      });
    }
  },

  _query(latlng, geometry) {
    // 空间查询
    let dataSetName = "";
    if (this.regiontype === "1") {
      // 普通区划要根据区划等级去获取查询的面数据集
      dataSetName = sgisRegionBase.regionUtils.getDataSetNameByRegionLevel(
        parseInt(this.level)
      );
    } else {
      // 特色区划及高新区要指定查询面数据集
      if (this.tsDtaSetName === "") {
        console.log("未指定要查询的特色区面");
        return;
      }
      dataSetName = this.tsDtaSetName;
    }
    if (dataSetName === "") {
      console.log("未获取到区划面数据");
      return;
    }
    if (this.currSpatialType === this.spatialTypes.SPATIAL) {
      // 如果是建筑物 ST_P_BU 则直接走快速查询，现在没有建筑物面，后续如果有建筑物面，此处正常走空间查询
      if (dataSetName === "ST_P_BU"){
        this._quckQuery(geometry, dataSetName);
      } else {
        this._spatialQueryByLevel(geometry, dataSetName);
      }
    } else if (this.currSpatialType === this.spatialTypes.BUFFER) {
      // 缓冲分析
      this._bufferQuery(geometry, dataSetName, this.bufferDistance);
    } else if (this.currSpatialType === this.spatialTypes.VICINITY) {
      this._cicinityQuery(geometry, dataSetName);
      // 邻域分析
    } else if (this.currSpatialType === this.spatialTypes.QUICK) {
      // 快速查询
      this._quckQuery(geometry, dataSetName);
    }
  },
  // 清除绘制的图形元素
  clearDrawFeatures() {
    if(this.lastDraw){
      this.DrawCon.delete(this.lastDraw.id);
    }
    // if(!this.isMeasure){
    //   hlLayer.clearHLLayer(this.activeMap);
    // }
    // //移除量算绘制标签
    // this.clearMeasured(this.activeMap);

    //移除缓冲图形
    this.clearBufferLayer(this.activeMap);
  },
  clearAllDrawFeatures(){
    if(!this.isMeasure){
      hlLayer.clearHLLayer(this.activeMap);
    }
    //移除量算绘制标签
    this.clearMeasured(this.activeMap);
  },
  // 如果是查询特色区划面的话需要设置一下特色区划的数据集名称
  setDataSetName(dataSetName) {
    this.tsDtaSetName = dataSetName;
  },
  // 如果缓冲分析使用地物的话，则要设置一下地物所在的面
  setBufferDataSetName(bufferDataSetName) {
    this.bufferDataSetName = bufferDataSetName;
  },
  /**
   * 绘制进行空间查询
   * @param { String } drawType 绘制类型
   * @param { String } level 区划等级   "0" "1" "2" "3" "4" "5" "6"
   * @param { String } regiontype 查询的区划类型 "1" = 普通区划 2 = 高新区 3= 特色区划
   * 高新区和特色区划要设置一下使用的面数据集名称,即在调用本方法前，调用setDataSetName设置一下特色区数据集名称
   */
  drawSpatialQuery(drawType, level, regiontype) {
    // 清除上一次绘制
    this.clearDrawFeatures();
    this.currSpatialType = this.spatialTypes.SPATIAL; // 查询类型
    this.level = level;
    this.regiontype = regiontype === "" ? "1" : regiontype;
    switch (drawType) {
      case this.drawType.CIRCLEMARKER:
        this._circleMarkerDraw();
        return;
      case this.drawType.POLINE:
        this._polineDraw();
        return;
      case this.drawType.POLYGON:
        this._polygonDraw();
        return;
      case this.drawType.RECTANGLE:
        this._rectangleDraw();
        return;
      case this.drawType.CIRCLE:
        this._circleDraw();
        return;
      default:
        return;
    }
  },
  /**
   * 邻域分析
   * @param { String } level 区划等级   "0" "1" "2" "3" "4" "5" "6"
   * @param { String } regiontype 查询的区划类型 "1" = 普通区划 2 = 高新区 3= 特色区划
   * 高新区和特色区划要设置一下使用的面数据集名称
   */
  drawVicinityQuery(level, regiontype) {
    // 清除上一次绘制
    this.clearDrawFeatures();
    this.level = level;
    this.regiontype = regiontype === "" ? "1" : regiontype;
    this.currSpatialType = this.spatialTypes.VICINITY;
    this._circleMarkerDraw();
  },
  /**
   * 缓冲分析
   * @param {String} level 区划等级
   * @param {String} regiontype 区划类型
   * @param {String} buffType 缓冲分析类型 缓冲分析类型为两种:绘制   选择地物
   * @param {Number} bufferDistance  缓冲距离    1  = 1千米
   */
  drawBufferQuery(level, regiontype, buffType, bufferDistance) {
    // 清除上一次绘制
    this.clearDrawFeatures();
    this.level = level;
    this.regiontype = regiontype === "" ? "1" : regiontype;
    this.currSpatialType = this.spatialTypes.BUFFER;
    this.currBufferType = buffType;
    this.bufferDistance = bufferDistance;
    this._polineDraw();
  },
  /**
   * 缓冲分析-点
   * @param {String} level 区划等级
   * @param {String} regiontype 区划类型
   * @param {String} buffType 缓冲分析类型 缓冲分析类型为两种:绘制   选择地物
   * @param {Number} bufferDistance  缓冲距离
   */
  drawBufferQuery_circleMarker(level, regiontype, buffType, bufferDistance) {
    // 清除上一次绘制
    this.clearDrawFeatures()
    this.level = level
    this.regiontype = regiontype === '' ? '1' : regiontype
    this.currSpatialType = this.spatialTypes.BUFFER
    this.currBufferType = buffType
    this.bufferDistance = bufferDistance
    this._circleMarkerDraw()
  },
  /**
   * 缓冲分析-周边查询
   * @param {String} level 区划等级
   * @param {String} regiontype 区划类型
   * @param {String} buffType 缓冲分析类型 缓冲分析类型为两种:绘制   选择地物
   * @param {Number} bufferDistance  缓冲距离
   */
  drawBufferQuery_zhoubian(level, regiontype, buffType, bufferDistance,geometry) {
    // 清除上一次绘制
    this.clearDrawFeatures()
    this.level = level
    this.regiontype = regiontype === '' ? '1' : regiontype
    this.currSpatialType = this.spatialTypes.BUFFER
    this.currBufferType = buffType
    this.bufferDistance = bufferDistance
    this._query(null, geometry);
  },

  /**
   * 缓冲分析-线
   * @param {String} level 区划等级
   * @param {String} regiontype 区划类型
   * @param {String} buffType 缓冲分析类型 缓冲分析类型为两种:绘制   选择地物
   * @param {Number} bufferDistance  缓冲距离
   */
  drawBufferQuery_poline(level, regiontype, buffType, bufferDistance) {
    // 清除上一次绘制
    this.clearDrawFeatures()
    this.level = level
    this.regiontype = regiontype === '' ? '1' : regiontype
    this.currSpatialType = this.spatialTypes.BUFFER
    this.currBufferType = buffType
    this.bufferDistance = bufferDistance
    this._polineDraw()
  },
  /**
   * 缓冲分析-多边形
   * @param {String} level 区划等级
   * @param {String} regiontype 区划类型
   * @param {String} buffType 缓冲分析类型 缓冲分析类型为两种:绘制   选择地物
   * @param {Number} bufferDistance  缓冲距离
   */
  drawBufferQuery_polygon(level, regiontype, buffType, bufferDistance) {
    // 清除上一次绘制
    this.clearDrawFeatures()
    this.level = level
    this.regiontype = regiontype === '' ? '1' : regiontype
    this.currSpatialType = this.spatialTypes.BUFFER
    this.currBufferType = buffType
    this.bufferDistance = bufferDistance
    this._polygonDraw()
  },
  addBufferLayer(geometry,map){
    let geoData ={
      "type": "geojson",
      "data":null
    };
    geoData.data = geometry;
    this.clearBufferLayer(map);
    map.addSource("buffer-hl-source-map", geoData);
    map.addLayer({
      "id": "buffer-hl-layer-map",
      "type": "line",
      "source": "buffer-hl-source-map",
      "paint": {
        // "line-color": "hsl(351,69%,40%)",
        "line-color": "rgb(234,56,45)",
        "line-width": {
          "base": 1.2,
          "stops": [
            [13,1.8],
            [20,20]
          ]
        },
        "line-opacity": 0.9
      },
    });
  },
  clearBufferLayer(map){
    if(map.getLayer("buffer-hl-layer-map") !== null && map.getLayer("buffer-hl-layer-map") !== undefined){
      map.removeLayer("buffer-hl-layer-map");
    }
    if(map.getSource("buffer-hl-source-map") !== null && map.getSource("buffer-hl-source-map") !== undefined){
      map.removeSource("buffer-hl-source-map");
    }
  },
  //量算操作
  drawToMeasure(drawType){
    // 清除上一次绘制
    this.isMeasure = true;
    this.clearDrawFeatures();
    switch (drawType){
      case "POLINE":
        this.DrawCon.changeMode('draw_line_string');
        break;
      case "POLYGON":
        this.DrawCon.changeMode('draw_polygon');
        break;
      default:
        break;
    }
  },
  /**
   * 添加绘制测距、测面结果
   * @param {Object} geo 几何类型 分为线和面
   */
  measured(param,map){
    this.clearMeasured(map);
    let measureEle = document.createElement('div');//显示测量结果元素
    measureEle.id = "measure-"  + map._container.id;
    let context = "";
    if(param.geometry.type == "LineString"){
      var distance = turf.lineDistance(param);
      distance = Number(distance).toFixed(2);
      context = '总共: ' + distance + '千米';
    }else if(param.geometry.type == "Polygon"){
      var area = turf.area(param);
      var rounded_area = (Math.round(area*100)/100)/1000000;
      rounded_area = rounded_area.toFixed(2);

      context = '总共: ' + rounded_area + '平方千米';
    }
    measureEle.innerHTML = "<div style=\"cursor:hand;    -webkit-border-radius: 1em!important;\n" +
      "    -moz-box-shadow: 3px 3px 6px #666;\n" +
      "    box-shadow: 3px 3px 6px #666;\"><table class=\"cunLabel\" style=\"border-collapse: collapse;\"><tbody><tr style=\"background-color: rgba(46,57,59,0.79);height:8px;\"><td height=\"20px\"><div style=\"font-size:14px;color:white;white-space:nowrap;position:relative;padding: 4px 10px;\">"+context+"</div></td></tr></tbody></table></div>";
    let length = param.geometry.coordinates.length;
    if(length > 0){
      let markerPoint =  null;
      if(param.geometry.type == "LineString"){
        markerPoint =  param.geometry.coordinates[1];
      }else if(param.geometry.type == "Polygon"){
        markerPoint =  param.geometry.coordinates[0][length - 1];
      }
      new mapboxgl.Marker(measureEle, { offset: [-50 / 2, -50 / 2] })
        .setLngLat([markerPoint[0],markerPoint[1]])
        .addTo(map);
    }
  },
  /**
   * 清除添加绘制测距、测面结果
   */
  clearMeasured(map){
    let id = "#measure-" + map._container.id;
    var node = $(id)
    if(node !== null){
      node.remove();
    }
  },
  /**
   * 切换区划标签显隐
   */
  ZoneMarkerShow(zoneShow){
    regionLable.toggleLayer(this.activeMap);
  }
};
